package pt.utl.ist.project_ccu;

import java.util.ArrayList;
import java.util.Set;
import java.util.TreeMap;

import pt.utl.ist.project_ccu.android_libs.Photo;
import pt.utl.ist.project_ccu.android_libs.SavedData;
import pt.utl.ist.project_ccu.android_libs.Tag;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TableLayout;
import android.widget.TableRow;

public class SearchPhotos extends Activity {
	
	private final int MAX_NUMBER_OF_TAGS = 5;
	TableLayout _tl;
	Spinner _spinner1;
	Spinner _spinner2;
	Button _searchButton;
	Button _addTagsButton;
	TreeMap<Integer,Spinner> _spinnerMap = new TreeMap<Integer,Spinner>();
	TreeMap<Integer,String> _tagSelectedMap = new TreeMap<Integer,String>();
	TreeMap<Integer,String> _tagTypeMap = new TreeMap<Integer,String>();
	TreeMap<Integer,TableRow> _tableRows = new TreeMap<Integer,TableRow>();
	AlertDialog myAlertDialog;
	Activity thisActivity;
	
	TableRow _buttonTableRow;
	Integer _spinnerCount = 0;
	int _tagsLimit = 0;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        thisActivity = this;
        setContentView(R.layout.activity_search_photos);
        SavedData.getInstance().updateActivity(this);
        _addTagsButton = new Button(this);
        _addTagsButton.setBackgroundResource(R.drawable.ic_add_icon);
        _buttonTableRow = createButtonRow();
        _searchButton = (Button) findViewById(R.id.searchButton);
        _searchButton.setOnClickListener(new OnClickListener() {
        	public void onClick(View v) {
        		Set<Integer> keys = _tagSelectedMap.keySet();
        		ArrayList<Tag> tags = new ArrayList<Tag>();
        		for (Integer i : keys) {
        			String tagName = _tagSelectedMap.get(i);
        			String tagType = _tagTypeMap.get(i);
        			if(!tagName.equals("")) {
        				tags.add(new Tag(tagType,tagName));
        			}
        		}
        		ArrayList<Photo> photos = SavedData.getInstance().getPhotosByTags(tags);
        		Intent intent = new Intent(getApplicationContext(), SearchPhotoResults.class);
        		intent.putExtra("Tags Selected", tags);
        		intent.putExtra("Photos", photos);
        		if(!photos.isEmpty()) {
        			startActivity(intent);
        		}
        		else {
        			showDialog(thisActivity);
        		}
        	}
        });
        _addTagsButton.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				createRow();
				
			}
		});
        _tl = (TableLayout) findViewById(R.id.tableLayout);
        createRow();
        setDeleteButtonVisibility(false);
        
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_search_photos, menu);
        return true;
    }
    

	
	private void addRow() {
		int[] screenDimensions = SavedData.getInstance().getScreenDimensions();
		int spinnerWidth = (int) (screenDimensions[0] * 0.4);
		int spinnerWidth_Text = (int) (screenDimensions[0] * 0.5);
        TableRow tr = new TableRow(this);
        _tableRows.put(_spinnerCount, tr);
        if(_tl.getChildCount() > 1) {
        	_tl.removeViewAt(_tl.getChildCount() - 1);
        }
        Spinner tagType = new Spinner(this);
        tagType.setTag(_spinnerCount);
        tagType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            public void onItemSelected(AdapterView<?> adapterView, View view, int pos, long l) {

            	Integer spinnerNumber = (Integer) adapterView.getTag();
            	String tag = adapterView.getItemAtPosition(pos).toString();
            	_tagTypeMap.put(spinnerNumber, tag);
            	if(tag != "") {
            		ArrayAdapter<String> tags = new ArrayAdapter<String>(getApplicationContext(),R.layout.spinner_item,SavedData.getInstance().getTagNames(tag));
            		tags.setDropDownViewResource(R.layout.spinner_dropdown_item);
            		_spinnerMap.get(spinnerNumber).setAdapter(tags);
            	}
            } 

            public void onNothingSelected(AdapterView<?> adapterView) {
                return;
            } 
        }); 
        ArrayList<String> tagsTypes =  (ArrayList<String>) SavedData.getInstance().getAllTags();
        ArrayAdapter<String> tagTypesList = new ArrayAdapter<String>(this,R.layout.spinner_item,tagsTypes);
        tagTypesList.setDropDownViewResource(R.layout.spinner_dropdown_item);
        
        tagType.setAdapter(tagTypesList);
        Spinner tagName = new Spinner(this);
        tagName.setTag(_spinnerCount);
        _spinnerMap.put(_spinnerCount,tagName);
        tagName.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        	public void onItemSelected(AdapterView<?> adapterView, View view, int pos, long l) {
            	Integer spinnerNumber = (Integer) adapterView.getTag();
            	String tagName = adapterView.getItemAtPosition(pos).toString();
        		_tagSelectedMap.put(spinnerNumber, tagName);
            } 

            public void onNothingSelected(AdapterView<?> adapterView) {
                return;
            } 
        });
        TableRow.LayoutParams params1 = new TableRow.LayoutParams(
        		spinnerWidth,
                TableRow.LayoutParams.FILL_PARENT);
        TableRow.LayoutParams params2 = new TableRow.LayoutParams(
        		spinnerWidth_Text,
                TableRow.LayoutParams.FILL_PARENT);
        TableRow.LayoutParams params3 = new TableRow.LayoutParams(
        		 TableRow.LayoutParams.FILL_PARENT,
                TableRow.LayoutParams.FILL_PARENT);
        tr.addView(tagType, params1);
        tr.addView(tagName, params2);
        tr.addView(new MyRelativeLayout(this,_spinnerCount),params3);
        TableLayout.LayoutParams trParams = new TableLayout.LayoutParams(
                TableLayout.LayoutParams.FILL_PARENT,
                TableLayout.LayoutParams.FILL_PARENT);
        _tl.addView(tr, trParams);
        TableLayout.LayoutParams tr2Params = new TableLayout.LayoutParams(
                TableLayout.LayoutParams.WRAP_CONTENT,
                TableLayout.LayoutParams.WRAP_CONTENT);
        _tl.addView(_buttonTableRow,tr2Params);
        
        
        if(_tl.getChildCount() > 2 ) {
        	setDeleteButtonVisibility(true);
        }
        _spinnerCount++;
        _tagsLimit++;
        if(_tagsLimit >= MAX_NUMBER_OF_TAGS) {
        	_addTagsButton.setVisibility(View.GONE);
        }
	}
	
	private void createRow() {
		_tagSelectedMap.put(_spinnerCount, "");
		addRow();

	}
	
	protected void setDeleteButtonVisibility(boolean visi) {
		for(int i = 0; i < _tl.getChildCount(); i++) {
			TableRow tr = (TableRow) _tl.getChildAt(i);
			if(tr.getChildCount() == 3) {
				Button button = (Button) ((RelativeLayout)tr.getChildAt(2)).getChildAt(0);
				if(visi) {
					button.setVisibility(View.VISIBLE);
				}
				else {
					button.setVisibility(View.GONE);
				}
			}
		}
	}
	
	private void showDialog(Context context) {
        if( myAlertDialog != null && myAlertDialog.isShowing() ) return;

        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setTitle("Search Photos");
        builder.setMessage("Photos not found.");
        builder.setPositiveButton("ok", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int arg1) {
                    dialog.dismiss();
                }});
        builder.setCancelable(false);
        myAlertDialog = builder.create();
        try {
        	myAlertDialog.show();
        }
        catch(Exception e) {}
	}
	
	private TableRow createButtonRow() {
		FrameLayout fl = new FrameLayout(this);
		int[] screenDimensions = SavedData.getInstance().getScreenDimensions();
		int buttonSize = (int) (screenDimensions[0] * 0.1);
		TableRow tr = new TableRow(this);
        TableRow.LayoutParams params = new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT,TableRow.LayoutParams.FILL_PARENT);
        fl.addView(_addTagsButton, params);
        tr.addView(fl);
		ViewGroup.LayoutParams parB = _addTagsButton.getLayoutParams();
		parB.height = buttonSize;
		parB.width = buttonSize;
		_addTagsButton.setLayoutParams(parB);
		
        return tr;
	}
	
	public class DeleteButton extends Button {
		
		public DeleteButton(Context context, int id) {
			super(context);
			this.setId(id);
			this.setBackgroundResource(R.drawable.delete_icon);
			final int buttonId = this.getId();
			this.setOnClickListener(new OnClickListener() {
				
				public void onClick(View v) {
					_tagsLimit--;
					if(_tagsLimit < MAX_NUMBER_OF_TAGS) {
						_addTagsButton.setVisibility(View.VISIBLE);
					}
					if(_tl.getChildCount() > 2) {
						_tagSelectedMap.remove(buttonId);
						_tagTypeMap.remove(buttonId);
						_spinnerMap.remove(buttonId);
						_tl.removeView(_tableRows.get(buttonId));	
						_tableRows.remove(buttonId);
					}
					if(_tl.getChildCount() == 2) {
						setDeleteButtonVisibility(false);
					}
				}
			});
		}
	}
	
	public class MyRelativeLayout extends RelativeLayout {
	
		public MyRelativeLayout(Context context, int id) {
			super(context);
			View dl = new DeleteButton(context, id);
			addView(dl);
			RelativeLayout.LayoutParams parB = (RelativeLayout.LayoutParams) dl.getLayoutParams();
			int[] screenDimensions = SavedData.getInstance().getScreenDimensions();
			int buttonSize = (int) (screenDimensions[0] * 0.1);
			parB.height = buttonSize;
			parB.width = buttonSize;
			parB.addRule(RelativeLayout.CENTER_IN_PARENT, 1);
			dl.setLayoutParams(parB);
			
		}

		
	}
    
}
